import React, {Component, PropTypes} from 'react';
import {Tree} from 'antd';
import 'whatwg-fetch';
import {getSubTree} from "../../services/showServer";
const TreeNode = Tree.TreeNode;

class TreeContainer extends Component {

  constructor(props) {
    super(props);
    this.state = {
      treeData: {
        "id": "0",
        "name": "主题",
        "children": []
      },
    };
  }

  onSelect(info) {
    this.props.signal.dispatch(info);
  }

  fetch() {
    fetch("/api/subject/subTree", {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    }).then(function (response) {
      if (response.ok) {
        return response.json();
      } else {
        alert("status : " + response.status);
      }
    }).then(function (json) {
      this.setState({
        treeData: {
          "id": "0",
          "name": "主题",
          "children": [
            {
              "id": "0",
              "name": "主题2",
              "children": []
            }
          ]
        },
      });
      this.state.data = JSON.stringify(json)
    }.bind(this))
  }

  componentDidMount() {
    // this.fetch();
    getSubTree().then(function (json) {
      this.setState({
        treeData: json
      });
    }.bind(this));
  }

  render() {
    const loop = data => data.map((item) => {
      if (item.children) {
        return <TreeNode title={item.name} key={item.id}>{loop(item.children)}</TreeNode>;
      }
      return <TreeNode title={item.name} key={item.id}/>;
    });

    const treeNodes = loop(this.state.treeData.children);

    return (
      <Tree className="myCls" showLine
            onSelect={this.onSelect.bind(this)}
      >
        {treeNodes}
      </Tree>
    );
  }
}

export default TreeContainer;
